﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WindowsLive.Writer.Api;
using System.Net;
using System.Drawing.Imaging;
using WordPress.Net;
using System.Linq;
using System.IO;
using System.Xml;

namespace WordpressFeaturedImagePlugin
{
    public partial class frmPublishing : Form
    {
        static string m_username, m_password, m_imagePath, m_publishUrl, m_postId = string.Empty;
        bool m_publish, m_postAsImage;
        BackgroundWorker pubWorker;

        public frmPublishing(string username, string password, string imagePath, string publishUrl, string postId, bool publish, bool postAsImage)
        {
            InitializeComponent();
            m_username = username;
            m_password = password;
            m_imagePath = imagePath;
            m_publishUrl = publishUrl;
            m_postId = postId;
            m_publish = publish;
            m_postAsImage = postAsImage;
            pubWorker = new BackgroundWorker { WorkerSupportsCancellation = false, WorkerReportsProgress = false };
            pubWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(pubWorker_RunWorkerCompleted);
            pubWorker.DoWork += new DoWorkEventHandler(pubWorker_DoWork);
        }

        public void GoBatman()
        {
            pubWorker.RunWorkerAsync();
        }

        void pubWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            WP wordpress = new WP { Proxy = PluginHttpRequest.GetWriterProxy(), Url = m_publishUrl };

            // Convert the image for posting
            MediaObject media = new MediaObject();
            FileInfo info = new FileInfo(m_imagePath);
            //string extn = m_imagePath.Substring(m_imagePath.LastIndexOf("."), m_imagePath.Length - m_imagePath.LastIndexOf("."));
            string imgName = m_postId + info.Extension;
            ImageFormat format = ImageFormat.Jpeg;
            switch (info.Extension)
            {
                case ".jpg":
                    format = ImageFormat.Jpeg;
                    break;
                case ".jpeg":
                    format = ImageFormat.Jpeg;
                    break;
                case ".png":
                    format = ImageFormat.Png;
                    break;
                case ".gif":
                    format = ImageFormat.Gif;
                    break;
            }
            if (!m_postAsImage)
            {
                imgName = info.Name;                
            }
            Image img = Bitmap.FromFile(m_imagePath);
            media = new MediaObject()
            {
                name = imgName,
                type = "image/" + format.ToString().ToLower(),
                bits = WP.ConvertImageToByteArray(img, format),
                postid = Int32.Parse(m_postId)
            };

            //Post the image
            MediaObjectInfo minfo = wordpress.ScottMediaObject(1, m_username, m_password, media);
            //Get the just posted post
            Post post = wordpress.GetPost(m_postId, m_username, m_password);
            List<CustomField> cfList = post.custom_fields.ToList<CustomField>();
            var customfields = from c in post.custom_fields
                               where c.key == "_thumbnail_id"
                               select c;
            CustomField featureField;
            if (customfields.Count() == 0)
            {
                featureField = new CustomField("_thumbnail_id", minfo.id.ToString());
                cfList.Add(featureField);
            }
            else
            {
                featureField = (CustomField)customfields.FirstOrDefault();
                cfList.Remove(featureField);
                featureField.value = minfo.id.ToString();
                cfList.Add(featureField);
            }
            post.custom_fields = cfList.ToArray();

            wordpress.EditPost((int)post.postid, m_username, m_password, post, m_publish);
        }

        void pubWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("There was an error uploading the image, please make sure you've installed the WordPress plugin from http://bit.ly/ScottMediaObject \nThe error was: " + e.Error.Message,
                    "Error publishing image", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (e.Error.Message.ToLower().Contains("password"))
                    HasErrored = true;
            }
            else
            {
                HasErrored = false;
            }
            Close();
        }

        public bool HasErrored { get; private set; }
    }
}
